<template>
  <div>
    <el-tag
      v-for="(item, index) in levelList"
      :key="index"
      :class="$route.path === item.path ? 'tag tag-active' : 'tag tag-deactive'"
      :closable="item.meta.title !== '财务看板'"
      @close="closeTag(item)"
      @click="handleLink(item)"
    >
      {{ item.meta.title }}
    </el-tag>
  </div>
</template>

<script>
export default {
  data() {
    return {
      levelList: null,
    };
  },
  watch: {
    $route() {
      this.getRoutes();
    },
  },
  created() {
    const flag = sessionStorage.getItem("old_routes");
    if (!flag) {
      sessionStorage.setItem(
        "routes",
        JSON.stringify([{ path: "/kanban", meta: { title: "财务看板" } }])
      );
    } else {
      sessionStorage.setItem("routes", flag);
    }
    this.levelList = JSON.parse(sessionStorage.getItem("routes"));
  },
  updated() {
    sessionStorage.setItem("old_routes", JSON.stringify(this.levelList));
  },
  beforeDestroy() {
    sessionStorage.clear();
  },
  methods: {
    set(item) {
      sessionStorage.setItem("routes", JSON.stringify(item));
    },
    getRoutes() {
      const { path, meta } = this.$route;
      const item = {
        path: path,
        meta: meta,
      };
      const flag = this.levelList.some((i) => i.path === item.path);
      if (!flag) {
        this.levelList.push(item);
        this.set(this.levelList);
      }
    },
    closeTag(route) {
      const { path } = route;
      this.levelList = this.levelList.filter((item) => item.path !== path);
      this.set(this.levelList);
      if (path === this.$route.path) {
        if (this.$router.history.length > 1) {
          this.$router.go(-1);
        } else {
          this.handleLink(this.levelList[this.levelList.length - 1]);
        }
      }
    },
    handleLink(route) {
      const { path } = route;
      if (path !== "/dashboard") {
        const item = this.levelList.find((item) => item.path === path);
        const index = this.levelList.indexOf(item);
        if (index !== -1) {
          const removedItem = this.levelList.splice(index, 1)[0];
          this.levelList.push(removedItem);
          this.set(this.levelList);
        }
      }
      this.$router.push({
        path: path,
      });
    },
  },
};
</script>
<style>
.tag {
  margin: 10px;
  cursor: pointer;
}

.tag-active {
  background-color: #ecf5ff !important;
  color: #409eff !important;
}

.tag-deactive {
  background-color: rgb(255, 255, 255) !important;
  color: rgb(114, 110, 110) !important;
}
</style>
